// 访客统计API服务
const express = require('express');
const router = express.Router();
const Visitor = require('../models/Visitor');

// 记录访客事件
router.post('/visitor/events', async (req, res) => {
    try {
        const eventData = {
            visitor_id: req.body.visitor_id || req.ip,
            session_id: req.body.session_id,
            event_type: req.body.event_type || 'page_view',
            page_url: req.body.page_url,
            referrer: req.body.referrer,
            user_agent: req.headers['user-agent'],
            ip_address: req.ip,
            country: req.body.country,
            device_type: req.body.device_type,
            browser: req.body.browser,
            event_data: req.body.event_data || {}
        };
        
        const event = await Visitor.recordEvent(eventData);
        
        res.json({
            success: true,
            message: '事件记录成功',
            data: event
        });
    } catch (error) {
        console.error('记录访客事件失败:', error);
        res.status(500).json({
            success: false,
            message: '记录访客事件失败'
        });
    }
});

// 获取访客统计摘要
router.get('/visitor/analytics/summary', async (req, res) => {
    try {
        const { start_date, end_date } = req.query;
        
        // 默认查询最近30天
        const defaultStartDate = new Date();
        defaultStartDate.setDate(defaultStartDate.getDate() - 30);
        
        const startDate = start_date || defaultStartDate.toISOString().split('T')[0];
        const endDate = end_date || new Date().toISOString().split('T')[0];
        
        const summary = await Visitor.getSummary(startDate, endDate);
        
        res.json({
            success: true,
            data: summary,
            period: { start_date: startDate, end_date: endDate }
        });
    } catch (error) {
        console.error('获取访客统计摘要失败:', error);
        res.status(500).json({
            success: false,
            message: '获取访客统计摘要失败'
        });
    }
});

// 获取热门页面
router.get('/visitor/analytics/top-pages', async (req, res) => {
    try {
        const { start_date, end_date, limit = 10 } = req.query;
        
        const defaultStartDate = new Date();
        defaultStartDate.setDate(defaultStartDate.getDate() - 30);
        
        const startDate = start_date || defaultStartDate.toISOString().split('T')[0];
        const endDate = end_date || new Date().toISOString().split('T')[0];
        
        const topPages = await Visitor.getTopPages(startDate, endDate, parseInt(limit));
        
        res.json({
            success: true,
            data: topPages,
            period: { start_date: startDate, end_date: endDate }
        });
    } catch (error) {
        console.error('获取热门页面失败:', error);
        res.status(500).json({
            success: false,
            message: '获取热门页面失败'
        });
    }
});

// 获取地理分布
router.get('/visitor/analytics/geo-distribution', async (req, res) => {
    try {
        const { start_date, end_date } = req.query;
        
        const defaultStartDate = new Date();
        defaultStartDate.setDate(defaultStartDate.getDate() - 30);
        
        const startDate = start_date || defaultStartDate.toISOString().split('T')[0];
        const endDate = end_date || new Date().toISOString().split('T')[0];
        
        const geoDistribution = await Visitor.getGeoDistribution(startDate, endDate);
        
        res.json({
            success: true,
            data: geoDistribution,
            period: { start_date: startDate, end_date: endDate }
        });
    } catch (error) {
        console.error('获取地理分布失败:', error);
        res.status(500).json({
            success: false,
            message: '获取地理分布失败'
        });
    }
});

// 获取设备统计
router.get('/visitor/analytics/device-stats', async (req, res) => {
    try {
        const { start_date, end_date } = req.query;
        
        const defaultStartDate = new Date();
        defaultStartDate.setDate(defaultStartDate.getDate() - 30);
        
        const startDate = start_date || defaultStartDate.toISOString().split('T')[0];
        const endDate = end_date || new Date().toISOString().split('T')[0];
        
        const deviceStats = await Visitor.getDeviceStats(startDate, endDate);
        
        res.json({
            success: true,
            data: deviceStats,
            period: { start_date: startDate, end_date: endDate }
        });
    } catch (error) {
        console.error('获取设备统计失败:', error);
        res.status(500).json({
            success: false,
            message: '获取设备统计失败'
        });
    }
});

// 获取实时统计
router.get('/visitor/analytics/realtime', async (req, res) => {
    try {
        const { hours = 24 } = req.query;
        
        const realtimeStats = await Visitor.getRealTimeStats(parseInt(hours));
        
        res.json({
            success: true,
            data: realtimeStats,
            period: { hours: parseInt(hours) }
        });
    } catch (error) {
        console.error('获取实时统计失败:', error);
        res.status(500).json({
            success: false,
            message: '获取实时统计失败'
        });
    }
});

// 更新访客统计（用于后台任务）
router.post('/visitor/analytics/update-stats', async (req, res) => {
    try {
        const statsData = req.body;
        
        const updatedStats = await Visitor.updateStats(statsData);
        
        res.json({
            success: true,
            message: '统计更新成功',
            data: updatedStats
        });
    } catch (error) {
        console.error('更新访客统计失败:', error);
        res.status(500).json({
            success: false,
            message: '更新访客统计失败'
        });
    }
});

module.exports = router;